#include <iostream>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>

using std::cout;
using std::endl;
using std::string;

const int size = 1024;

// father read, son write

string getOtherMessage()
{
    static int cnt = 0;
    string messageid = std::to_string(cnt);
    cnt++;
    pid_t self_id = getpid();
    string stringpid = std::to_string(self_id);

    string message = "messageid: " + messageid + " my pid is:" + stringpid;
    return message;
}

void SubProcessRead(int rfd)
{
    char inbuffer[size];
    while (true)
    {
        ssize_t n = read(rfd, inbuffer, sizeof(inbuffer) - 1);
        if (n > 0)
        {
            inbuffer[n] = 0;
            cout << "son get message: " << inbuffer << endl;
        }
    }
}

void FatherProcessWrite(int wfd)
{
    string message = "son, I am your father process!";
    while (true)
    {
        string info = message + getOtherMessage();
        write(wfd, info.c_str(), info.size());

        sleep(1);
    }
}

int main()
{
    int pipefd[2];
    int n = pipe(pipefd);
    if (n < 0)
    {
        std::cerr << "errno: " << errno << "  " << "errstring: " << strerror(errno) << endl;
        return 1;
    }

    pid_t id = fork();
    if (id > 0)
    {
        cout << "父进程关闭不需要的fd, 准备发消息" << endl;
        sleep(1);

        close(pipefd[0]);

        FatherProcessWrite(pipefd[1]);

        close(pipefd[1]);
        exit(0);
    }
    else
    {
        cout << "子进程关闭不需要的fd, 准备收消息" << endl;
        sleep(1);
        close(pipefd[1]);

        SubProcessRead(pipefd[0]);

        close(pipefd[1]);
    }

    pid_t rid = waitpid(id, nullptr, 0);
    if (rid > 0)
        cout << "wait child process done" << endl;

    return 0;
}
